<?php defined('SYSPATH') or die('No direct access allowed.');

class Controller_CPanel_Files extends Controller_CPanel {

    public function action_index() {
        //Check forms

        $action = Arr::get($_POST, 'action', NULL);
        if ($action === NULL)
            $action = Arr::get($_GET, 'action', '');

        switch ($action) {
            case 'new_folder':
                $this->createFolder();
                break;
            case 'upload':
                $this->upload();
                break;
            default:
                break;
        }

        if (isset($_GET['remove'])) {
            $this->remove();
        } elseif (isset($_GET['getfile'])) {
            $this->printFile();
            return;
        } elseif (isset($_GET['view'])) {
            $this->viewFile();
            return;
        }

        //Render content

        $this->title = __('Files');
        $view = View::factory('cpanel/content/files');

        $settings = Kohana::$config->load('app');

        $root = Arr::get($_GET, 'root', '');

        $view->languages = Arr::get($settings, 'languages', array());
        $view->root = $root;
        $view->infos = $this->getInfos($root);

        $this->content = $view->render();
    }
    
    private function printFile() {
        $file = Arr::get($_GET, 'getfile', '');
        echo file_get_contents(realpath(DOCROOT . '..' . DIRECTORY_SEPARATOR . $file));
        die();
    }
    
    private function viewFile() {
        $root = Arr::get($_GET, 'root', '');
        $file = Arr::get($_GET, 'view', '');

        $path = realpath(DOCROOT . '..') . DIRECTORY_SEPARATOR;
        $path = $path . $root . DIRECTORY_SEPARATOR;
        $path = str_replace(DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path);

        if (!file_exists($path . $file)) {
            $this->add_message('File not found!', 'error');
            return;
        }
        
        $mime = 'unknown';
        $info = pathinfo($path . $file);
        switch ($info['extension']) {
            case 'png':
            case 'gif':
            case 'jpeg':
            case 'jpg':
            case 'ico':
                $mime = 'image';
                break;
            case 'htaccess':
            case 'txt':
            case 'js':
            case 'css':
            case 'htm':
            case 'html':
            case 'php':
                $mime = 'text';
                break;
        }
        
        
        //Render content

        $this->title = __('Files');
        $view = View::factory('cpanel/content/files_view');

        $settings = Kohana::$config->load('app');

        $root = Arr::get($_GET, 'root', '');

        $view->languages = Arr::get($settings, 'languages', array());
        $view->root = $root;
        $view->file = $file;
        $view->mime = $mime;

        $this->content = $view->render();
    }

    private function getInfos($root = '') {

        $path = realpath(DOCROOT . '..') . DIRECTORY_SEPARATOR;
        $path = $path . $root . DIRECTORY_SEPARATOR;
        $path = str_replace(DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path);

        $files = self::scandirSorted($path);
        $infos = array();

        foreach ($files as $file) {
            if ($file == '.' || $file == '..')
                continue;

            $file = $path . $file;
            $infos[] = array(
                'root' => $root,
                'file' => $file,
                'name' => basename($file),
                'modified' => date("d.m.Y G:i:s", filectime($file)),
                'permission' => substr(decoct(fileperms($file)), -3),
            );
        }

        return $infos;
    }

    public static function scandirSorted($path) {
        $sortedData = array();
        foreach (scandir($path) as $file) {
            if (is_file($path . $file)) {
                array_push($sortedData, $file);
            } else {
                array_unshift($sortedData, $file);
            }
        }
        return $sortedData;
    }

    private function createFolder() {
        $root = Arr::get($_GET, 'root', '');
        $name = Arr::get($_POST, 'name', '');

        $path = realpath(DOCROOT . '..') . DIRECTORY_SEPARATOR;
        $path = $path . $root . DIRECTORY_SEPARATOR;
        $path = str_replace(DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path);

        if (file_exists($path . $name)) {
            $this->add_message('Folder already exists!', 'error');
            return;
        }

        if (mkdir($path . $name)) {
            $this->add_message('Folder is created!', 'success');
        } else {
            $this->add_message('Can\'t create folder!', 'error');
        }
    }

    private function remove() {
        $root = Arr::get($_GET, 'root', '');
        $name = Arr::get($_GET, 'remove', '');

        $path = realpath(DOCROOT . '..') . DIRECTORY_SEPARATOR;
        $path = $path . $root . DIRECTORY_SEPARATOR;
        $path = str_replace(DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path);

        if (!file_exists($path . $name)) {
            $this->add_message('Not found!', 'error');
            return;
        }

        if (is_dir($path . $name)) {
            if (rmdir($path . $name)) {
                $this->add_message('Folder is removed!', 'success');
            } else {
                $this->add_message('Can\'t remove folder!', 'error');
            }
            return;
        }

        if (unlink($path . $name)) {
            $this->add_message('File is removed!', 'success');
        } else {
            $this->add_message('Can\'t remove file!', 'error');
        }
    }

    private function upload() {
        $root = Arr::get($_GET, 'root', '');

        $path = realpath(DOCROOT . '..') . DIRECTORY_SEPARATOR;
        $path = $path . $root . DIRECTORY_SEPARATOR;
        $path = str_replace(DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR, $path);

        if (is_file($path . $_FILES['file']['name'])) {
            $this->add_message('File already exists!', 'error');
            return;
        }
        
        $name = Upload::save($_FILES['file'], $_FILES['file']['name'], $path, 0777);
        
        if ($name != null) {
            $this->add_message('File is uploaded!', 'success');
        } else {
            $this->add_message('Can\'t upload file!', 'error');
        }
    }

}